<?php
/**
 * oscshop 电子商务系统
 *
 * ==========================================================================
 * @link      http://www.oscshop.cn/
 * @copyright Copyright (c) 2015 oscshop.cn. 
 * @license   http://www.oscshop.cn/license.html License
 * ==========================================================================
 *
 * @author    李梓钿
 *
 */
namespace Home\Controller;

class CartController extends CommonController {
	
	//结算
	function checkout(){
	
		$this->title='结算-';
		$this->meta_keywords=C('SITE_KEYWORDS');
		$this->meta_description=C('SITE_DESCRIPTION');		
		
		$cart=new \Lib\Cart();
		if ((!$cart->has_goods()) ) {
			$this->redirect('/cart');
			die;
		}

		$this->shipping_required =$cart->has_shipping();	
		$this->display();
	}
	
	//显示购物车中商品列表
	function show_cart_goods(){
		
		$cart=new \Lib\Cart();
		
		$this->goods=$cart->get_all_goods();
		
		$this->total_price=$cart->get_all_goods_price();
		
		$this->weight=$cart->getWeight();
		
		$this->display('index');
		
	}
	
	//更新购物车商品数量
	function update_quantity(){
		$d=I('post.');
		$cart=new \Lib\Cart();
		
		$product=M('goods')->find($d['id']);
		
		//商品存在
		if($product){
			$goods_quantity=$cart->get_goods_quantity($d['id']);

			if($goods_quantity<$d['q']){
				$json['error']='商品数量不足，剩余'.$goods_quantity.'个！！';
			}
			if (!$json) {
			
				$cart->update($d['id'],$d['q']);
				
				$total=$cart->count_goods();
				
				session('cart_total',$total);	
				
				$json['success']=$total;
				//商品价格
				$json['price']=$cart->get_goods_price_by_goods_quantity($d['id'],$d['q']);
				//单个商品总价
				$json['total_price']=$cart->get_total_price_by_goods_id($d['id'],$d['q']);
				//所有商品总价
				$json['total_all_price']=$cart->get_all_goods_price();
				//所有商品重量
				$json['weight']=$cart->getWeight();
			}
			$this->ajaxReturn($json);
			die;
		}

	}
	//删除商品
	function remove(){
		
		$cart=new \Lib\Cart();
		
		$cart->remove($_GET['id']);			
		
		$total=$cart->count_goods();
				
		session('cart_total',$total);
		
		$this->redirect('/cart');	
	}
	
	
	//加入购物车	
	function add(){
		$data=I('post.');
		
		if (isset($data['goods_id'])) {
			$goods_id = $data['goods_id'];
		} else {
			$goods_id = 0;
		}
		$product=M('goods')->find($goods_id);
		
		//商品存在
		if($product){
			
			$cart=new \Lib\Cart();
			
			if (isset($data['quantity'])) {
				$quantity = $data['quantity'];
			} else {
				$quantity = 1;
			}
			
			$goods_quantity=$cart->get_goods_quantity($goods_id);
		
			if($goods_quantity<$quantity){
				$json['error']='商品数量不足，剩余'.$goods_quantity.'个！！';
			}	
			
			if (!$json) {
				
				$cart->add($goods_id,$quantity);
				
				$total=$cart->count_goods();
				
				session('cart_total',$total);
				
				$json['success']='成功加入购物车！！';
				
				$json['total']=$total;
			}
			
			$this->ajaxReturn($json);
			die;
		}		
	}
    
}